/**
 * WhiMAIcpp - C++ interface for the Whiskey Media APIs.
 *  Copyright (C) 2010  Anders Bugge
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "interface.h"

// cURL
#include <curl\curl.h>
#include <curl\easy.h>

namespace WM
{

int Interface::count = 0;
Interface* Interface::instance = 0;

Interface* Interface::Instance()
{
	if( count == 0 )
		instance = new Interface();

	count++;
	return instance;

}
void Interface::Release()
{
	count--;

	// Release when no one is using
	if( count == 0 )
		delete instance;
}

unsigned int Interface::getData( std::string& data, const std::string& url )
{
	if( curl_handle == NULL )
		return CURLE_FAILED_INIT;

	// cURL setup - address
	CURLcode cCode;
	cCode = curl_easy_setopt( curl_handle, CURLOPT_URL, url.c_str() );
	if( cCode != CURLE_OK )
		return cCode;

	// cURL setup - callback
	cCode = curl_easy_setopt( curl_handle, CURLOPT_WRITEFUNCTION, write_data );
	if( cCode != CURLE_OK )
			return cCode;

	// perform request
	cCode = curl_easy_perform( curl_handle );
	if( cCode != CURLE_OK )
			return cCode;

	data = json;
	json.clear();
	return CURLE_OK;
}

Interface::Interface()
{
	json = "";

	// cURL initialization
	curl_handle = curl_easy_init();
}

Interface::~Interface()
{
	// cURL cleanup
	curl_easy_cleanup( curl_handle );
}

size_t Interface::write_data( void *ptr, size_t size, size_t nmemb, void *ourpointer )
{
	// append received data and return the size
	instance->json.append( (const char*)ptr, nmemb );
	return size * nmemb;
}

}
